#include "headfiles.h"

using namespace std;

int modBinSearch(int *array, int n, int num) {
    if (array == NULL ||
        n <= 0) {
        cout << "Invalid input argument, NULL!" << endl;
        return -1;
    }

    int l = 0;
    int r = n - 1;
    int mid;

    while (l <= r) {
        mid = (l + r) / 2;
        if (num == array[mid]) {
            return mid;
        }
        else if (num > array[mid]) {
            l = mid + 1;
        }
        else {
            r = mid - 1;
        }
    }

    if (l == n) {
        return n - 1;
    }

    if (r < 0) {
        return 0;
    }

    int dist1 = array[l] - num;
    dist1 = (dist1 > 0) ? dist1 : (-1) * dist1;

    int dist2 = array[r] - num;
    dist2 = (dist2 > 0) ? dist2 : (-1) * dist2;

    if (dist1 < dist2) {
        return l;
    }
    else {
        return r;
    }
}

